package com.itheima.d03_net_chat.server;

import java.io.*;
import java.net.Socket;
import java.util.*;

/**
 * 自定义线程任务类：
 *      负责和指定的客户端进行通信
 *
 * 设置规则：
 *      客户端消息格式：
 *          群聊：
 *              all:消息
 *          单聊：
 *              one:ip地址:消息
 */
public class ChatRunnable implements Runnable {

    private Socket socket;

    public ChatRunnable(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        //记录所有在线的客户端信息
        Server.onLineSockets.put(socket.getInetAddress().getHostAddress(), socket);
        System.out.println("当前在线人数："+Server.onLineSockets.size());

        try (
                //1.获取Socket的输入流对象
                InputStream is = socket.getInputStream();
                //把原始流包装成字符输入流，更好的读取字符文本数据
                BufferedReader br = new BufferedReader(new InputStreamReader(is));
        ) {

            //2.持续和当前客户端交互
            while (true) {

                String msg = br.readLine();
                System.out.println("接收到"+socket.getInetAddress().getHostAddress()+"客户端的消息：" + msg);

                //3.判断聊天的形式
                if(msg.startsWith("all:")){
                    //群聊
                    sendMsgToAll(msg);
                }else if(msg.startsWith("one:")){
                    //单聊
                }else{
                    //和服务器聊天
                }


                if (Objects.equals(msg, "886")) {
                    System.out.println(socket.getRemoteSocketAddress()+"：客户端强制退出...");
                    Server.onLineSockets.remove(socket.getInetAddress().getHostAddress());
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            Server.onLineSockets.remove(socket.getInetAddress().getHostAddress());
            System.out.println(socket.getRemoteSocketAddress()+"：客户端强制退出...");
        }
    }

    /**
     * 群聊
     * @param msg
     */
    private void sendMsgToAll(String msg) throws IOException {
        //1.获取所有在线的客户端socket
        Set<Map.Entry<String, Socket>> entries = Server.onLineSockets.entrySet();
        for (Map.Entry<String, Socket>  entry :   entries) {
            String ip = entry.getKey();
            Socket socket = entry.getValue();
            //群聊，排除掉自己
            if("127.0.0.1".equals( ip )){
                continue;
            }
            //2.遍历所有socket，获取每一个socket的输出流
            OutputStream os = socket.getOutputStream();
            PrintWriter pw = new PrintWriter(os);

            //3.转发消息给对应的客户端
            pw.println( msg );
            pw.flush();
        }
    }

}



















